/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.purpose.service.impl;

import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.purpose.domain.KPITemplate;
import com.koron.purpose.mapper.KPITemplateMapper;
import com.koron.purpose.service.api.KPITemplateService;
import com.koron.purpose.utils.BusinessCode;
import org.apache.commons.lang3.StringUtils;

import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class KPITemplateServiceImpl implements KPITemplateService {

    private final static  Logger logger = LoggerFactory.getLogger(KPITemplateServiceImpl.class);

    @Override
    public DataBean<KPITemplate> fetchKPITemplates(String year, String name,Integer negatively,Integer start, Integer rows) {
        if (logger.isDebugEnabled()) {
            logger.debug("year = {}, name = {}", year, name);
        }
        try (SessionFactory factory = new SessionFactory()) {
            KPITemplateMapper mapper = factory.getMapper(KPITemplateMapper.class);
            List<KPITemplate> kpiTemplates = mapper.queryByCondition(year, name,negatively, start, rows);
            DataBean<KPITemplate> dataBean = new DataBean<>();
            dataBean.setList(kpiTemplates);
            if (start != null && rows != null){
                Integer total = mapper.countByCondition(year, name,negatively);
                dataBean.setPageSize(rows);
                dataBean.setTotalNumber(total);
                dataBean.setTotalPage(total > rows ? (total % rows == 0? total/rows : total/rows + 1) : 1);
                dataBean.setPageNo(start / rows + 1);
            }
            return dataBean;
        }
    }

    @Override
    public KPITemplate fetchOne(String id) {
        if (logger.isDebugEnabled()) {
            logger.debug("id = {}", id);
        }
        try (SessionFactory factory = new SessionFactory()) {
            return factory.getMapper(KPITemplateMapper.class).queryOne(id);
        }
    }

    @Override
    public Boolean batchDetele(List<String> idList) {
        try (SessionFactory factory = new SessionFactory()) {
            return factory.getMapper(KPITemplateMapper.class).batchDetele(idList) >= 0;
        }
    }

    @Override
    public Integer persist(KPITemplate template) {
        try (SessionFactory factory = new SessionFactory()) {
            Integer start = null, rows = null;
            KPITemplate dest = null;
            KPITemplate dest2=null;//检查code是否唯一
            List<KPITemplate> kpiTemplateList=new ArrayList<>();
            KPITemplateMapper mapper = factory.getMapper(KPITemplateMapper.class);
            List<KPITemplate> kpiTemplates = mapper.queryByCondition(template.getYear(),template.getName(),template.getNegatively(),start, rows);
            if (kpiTemplates != null && !kpiTemplates.isEmpty()) {
                kpiTemplates = kpiTemplates.stream().filter(t -> t.getName().equals(template.getName())).collect(Collectors.toList());
                dest = !kpiTemplates.isEmpty()? kpiTemplates.get(0) : null;
            }
            if (StringUtils.isBlank(template.getId())) {
                if (dest != null) {
                    return BusinessCode.KPI_NAME_DUP.getCode();
                }
                template.setId(DefaultIdGenerator.getInstance().generateLongId());
                //设置唯一编码,唯一编码要求4位数字
                //先查询目前表中最大的code
                String maxCode=mapper.queryMaxCode();
                int maxValue=Integer.parseInt(maxCode)+1;
                template.setCode(String.format("%04d",maxValue));
                if (mapper.insert(template) > 0) {
                    return BusinessCode.SUCCESS.getCode();
                }
            } else {
                if (dest != null && !dest.getId().equals(template.getId())) {
                    return BusinessCode.KPI_NAME_DUP.getCode();
                }
                //修改时，检查编码是否唯一
                if (kpiTemplates != null && !kpiTemplates.isEmpty()) {
                    if (StringUtils.isNotEmpty(template.getCode())) {
                        kpiTemplateList = kpiTemplates.stream().filter(t -> t.getCode().equals(template.getCode())).collect(Collectors.toList());
                        dest2 = (!kpiTemplateList.isEmpty() && kpiTemplateList.size() > 0) ? kpiTemplateList.get(0) : null;
                    }
                    if (dest2!=null&&!dest2.getCode().equals(template.getCode())){
                        return BusinessCode.KPI_CODE_DUP.getCode();
                    }
                }
                if(mapper.update(template) > 0) {
                    return BusinessCode.SUCCESS.getCode();
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return BusinessCode.EXCEPTION.getCode();
    }



}
